Page({
  data: {
    stopwatch: {
      // 分钟
      minutes: 0,
      // 秒
      seconds: 0,
      // 毫秒
      milliseconds: 0,
      // 是否计时
      isRunning: false,
      // 定时器
      timer: null,
      // 分段
      laps: [],
      // 滚动最新记录
      scrollToLapId: '',
      diff: 0
    }
  },

  onLoad() {
    // 初始化数据
    this.resetStopwatch();
  },

  onUnload() {
    // 页面卸载时清除定时器
    this.clearStopwatchTimer();
  },

  formatStopwatchTime() {
    // 时间格式化
    const {minutes, seconds, milliseconds} = this.data.stopwatch;
    const displayMinutes = minutes.toString().padStart(2, '0');
    const displaySeconds = seconds.toString().padStart(2, '0');
    const displayMilliseconds = Math.floor(milliseconds / 10).toString().padStart(2, '0');
    
    return `${displayMinutes}:${displaySeconds}.${displayMilliseconds}`;
  },

  toggleStopwatch() {
    const stopwatch = {...this.data.stopwatch};
    // false 的 时候显示开始
    if (stopwatch.isRunning) {
      // 暂停秒表 true
      this.clearStopwatchTimer();
    } else {
      // 开始秒表 false
      this.startStopwatchTimer();
    }
  },

  startStopwatchTimer() {
    // 开始计时
    const stopwatch = {...this.data.stopwatch};
    stopwatch.timer = null
    stopwatch.timer = setInterval(() => {
      // 开始执行了
      let {minutes, seconds, milliseconds} = stopwatch;
      milliseconds += 100;
      if (milliseconds >= 1000) {
        milliseconds = 0;
        seconds++;
        if (seconds >= 60) {
          seconds = 0;
          minutes++;
        }
      }
      
      stopwatch.minutes = minutes;
      stopwatch.seconds = seconds;
      stopwatch.milliseconds = milliseconds;
      
      this.setData({
        stopwatch
      });
    }, 10); // 每10毫秒更新一次
    stopwatch.isRunning = true
    this.setData({
      stopwatch
    })
  },

  clearStopwatchTimer() {
    if (this.data.stopwatch.timer) {
      clearInterval(this.data.stopwatch.timer);
      const stopwatch = {...this.data.stopwatch};
      stopwatch.timer = null;
      stopwatch.isRunning = false
      this.setData({
        stopwatch
      })
    }
  },

  resetStopwatch() {
    // 重置秒表
    if (this.data.stopwatch.isRunning) return;
    const stopwatch = {
      minutes: 0,
      seconds: 0,
      milliseconds: 0,
      isRunning: false,
      timer: null,
      laps: [],
      scrollToLapId: ''
    };
    
    this.setData({
      stopwatch
    })
  },

  recordLap() {
    if (!this.data.stopwatch.isRunning) return;
  
    const stopwatch = { ...this.data.stopwatch };
    const currentTime = this.formatStopwatchTime();
    const lapId = stopwatch.laps.length + 1;
  
    // 1. 计算当前总毫秒数，用于计算差值
    const { minutes, seconds, milliseconds } = stopwatch;
    const totalMilliseconds = minutes * 60 * 1000 + seconds * 1000 + milliseconds;
  
    // 2. 计算与上一段的差值
    let diffTime = "00:00.00"; // 默认差值为0
    if (stopwatch.laps.length > 0) {
      // 获取上一次记录的总毫秒数
      const lastLapTotalMs = stopwatch.laps[0].totalMilliseconds;
      // 计算差值（毫秒）
      const diffMs = totalMilliseconds - lastLapTotalMs;
      // 将差值毫秒数格式化为 mm:ss.ss
      diffTime = this.formatTimeFromMs(diffMs);
    }
    // 3. 添加新的记录，包含当前时间、差值和总毫秒数
    stopwatch.laps.unshift({
      id: lapId,
      time: currentTime,
      diff: diffTime, // 新增：与上一段的差值
      totalMilliseconds: totalMilliseconds, // 新增：当前累计总毫秒数
    });
  
    // 设置滚动到最新记录
    stopwatch.scrollToLapId = `lap-${lapId}`;
  
    this.setData({
      stopwatch,
    });
    console.log(stopwatch, 'stopwatch')
  },
  /**
   * 将毫秒数格式化为 mm:ss.ss 的时间格式
   * @param {number} ms - 时间（毫秒）
   * @returns {string} 格式化后的时间字符串
   */
  formatTimeFromMs(ms) {
    const minutes = Math.floor(ms / 60000);
    const seconds = Math.floor((ms % 60000) / 1000);
    const milliseconds = Math.floor((ms % 1000) / 10); // 保留一位小数

    const displayMinutes = minutes.toString().padStart(2, "0");
    const displaySeconds = seconds.toString().padStart(2, "0");
    const displayMilliseconds = milliseconds.toString().padStart(1, "0");

    return `${displayMinutes}:${displaySeconds}.${displayMilliseconds}`;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      "stopwatch.timer": null
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({
      "stopwatch.timer": null
    });
  }
});    